<template>
	<BasicModal
		width="800px"
		title="预览"
		class="upload-preview-modal"
		v-bind="$attrs"
		@register="register"
		:showOkBtn="false"
		cancelText="确定"
	>
		<FileList :dataSource="fileListRef" :columns="columns" :actionColumn="actionColumn" />
	</BasicModal>
</template>
<script lang="ts">
import { defineComponent, watch, ref } from 'vue';
import FileList from './FileList.vue';
import { BasicModal, useModalInner } from '../../../Modal';
import { previewProps } from '../props';
import { PreviewFileItem } from '../types/typing';
import { createPreviewColumns, createPreviewActionColumn } from '../data';
import { isArray } from '@/utils/is';

export default defineComponent({
	components: { BasicModal, FileList },
	props: previewProps,
	emits: ['list-change', 'register', 'delete', 'preview', 'preview-download'],
	setup(props, { emit }) {
		const [register, { closeModal }] = useModalInner();

		const fileListRef = ref<PreviewFileItem[]>([]);
		watch(
			() => props.value,
			value => {
				if (!isArray(value)) value = [];
				fileListRef.value = value
					.filter(item => !!item)
					.map(item => {
						return {
							url: item,
							type: item.split('.').pop() || '',
							name: item.split('/').pop() || '',
						};
					});
			},
			{ immediate: true },
		);

		// 预览
		function handlePreview(record: PreviewFileItem) {
			const { url = '' } = record;
			emit('preview', url);
		}

		// 删除
		function handleRemove(record: PreviewFileItem) {
			const index = fileListRef.value.findIndex(item => item.url === record.url);
			if (index !== -1) {
				const removed = fileListRef.value.splice(index, 1);
				emit('delete', removed[0].url);
				emit(
					'list-change',
					fileListRef.value.map(item => item.url),
					'preview-delete',
				);
			}
		}

		// 下载
		function handleDownload(record: PreviewFileItem) {
			emit('preview-download', record);
		}

		return {
			register,
			closeModal,
			fileListRef,
			columns: createPreviewColumns() as any[],
			actionColumn: createPreviewActionColumn({ handlePreview, handleRemove, handleDownload }) as any,
		};
	},
});
</script>
<style lang="less">
.upload-preview-modal {
	.ant-upload-list {
		display: none;
	}

	.ant-table-wrapper .ant-spin-nested-loading {
		padding: 0;
	}
}
</style>
